
<?php

	function get_last_sunday($date)
	{
		while($date->format('l') != 'Sunday')
		{
			$date->modify('-1 days');
		}
		return $date;
	}
	
	function in_month($date, $month)
	{
		return $date->format('m') == $month;
	}
	
	function draw_week(&$date, $events)
	{
		$output="<tr>";
		for($i=1; $i<=7; $i++)
		{
			$output .="<td> ";
			if (in_month($date, $_GET['month']))
			{
				 $output.= $date->format('j'). draw_day($date, $events); 
			}
			$output.= "</td>";
			$date->modify('+1 days');
		}
		$output.="</tr>";
		return $output;
	}
	
	function draw_day($date, $events)
	{
		$date_str = $date->format('Y-m-d');
		$output="<ul>";
		
		if(array_key_exists($date_str, $events))
		{
			$todays_events = $events[$date_str];
			foreach($todays_events as $event)
			{
				$output.="<li>";
				if($event->belongs_to(current_user()))
				{
					$output.="<a href='?controller=Event&amp;action=edit&id=$event->id'>";
					$output.= $event->title;
					$output.="</a>";
				}
				else
				{
					$output.="<a href='?controller=Event&amp;action=detail&id=$event->id'>";
					$output.= $event->title;
					$output.="</a>";
				}
				$output.="</li>";
			}
		}
		$output .="</ul>";
		
		return $output;
	}
	
?>


<div id="month_nav">
	<span id="next_month">
		<a href="?controller=Event&amp;action=month_grid&amp;month=<?=$next_month->format('m') ?>&amp;year=<?= $next_month->format('Y') ?>">
			<?=$next_month->format('F Y') ?>
		</a>
	</span>
	<span id="previous_month">

		<a href="?controller=Event&amp;action=month_grid&amp;month=<?=$prev_month->format('m') ?>&amp;year=<?= $prev_month->format('Y') ?>">
			<?=$prev_month->format('F Y') ?>
		</a>
	</span>

</div>
<table class="monthgrid">
	<thead>
		<th>Sunday</th>
		<th>Monday</th>
		<th>Tuesday</th>
		<th>Wednesday</th>
		<th>Thursday</th>
		<th>Friday</th>
		<th>Saturday</th>
	</thead>
	<?php $date=get_last_sunday($from) ?>
	<?php 
	do
	{

		echo draw_week($date, $events);

		
	} while(in_month($date, $_GET['month'])) 
	?>
</table>
